package cn.juque.redoctopus.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.juque.common.base.BaseResponseVO;
import cn.juque.common.constants.MessageEnum;
import cn.juque.common.utils.CollectUtil;
import cn.juque.redoctopus.api.constants.OctopusMsgEnum;
import cn.juque.redoctopus.bo.LogBO;
import cn.juque.redoctopus.bo.LogDataGridBO;
import cn.juque.redoctopus.bo.LogSearchBO;
import cn.juque.redoctopus.bo.field.FieldDocBO;
import cn.juque.redoctopus.controller.vo.LogDataGridVO;
import cn.juque.redoctopus.controller.vo.LogSearchVO;
import cn.juque.redoctopus.controller.vo.LogVO;
import cn.juque.redoctopus.service.ILogService;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author nuoka
 * @version 1.0.0
 * <li></li>
 * @date 2021/11/7 21:36
 **/
@Slf4j
@Controller
@RequestMapping("/log")
public class LogController {

    @Resource
    private ILogService logService;

    /**
     * 查询接口
     * @param logSearchVO
     * @return
     */
    @PostMapping("/list")
    @ResponseBody
    public BaseResponseVO<LogDataGridVO<LogVO>> list(@RequestBody LogSearchVO logSearchVO) {
        try {
            LogSearchBO logSearchBO = new LogSearchBO();
            BeanUtil.copyProperties(logSearchVO, logSearchBO);
            LogDataGridBO<LogBO> dataGridBO = this.logService.listLog(logSearchBO);
            List<LogBO> boList = dataGridBO.getRows();
            List<LogVO> voList = boList.stream().map(t->{
                LogVO vo = new LogVO();
                BeanUtil.copyProperties(t, vo);
                vo.setLogTime(DateUtil.format(t.getTimestamp(), DatePattern.NORM_DATETIME_MS_PATTERN));
                return vo;
            }).collect(Collectors.toList());
            byte[] byteArray = ObjectUtil.serialize(dataGridBO.getLastDoc());
            LogDataGridVO<LogVO> logDataGridVO = new LogDataGridVO<>(voList, dataGridBO.getTotal(), Base64.encode(byteArray));
            return new BaseResponseVO<>(MessageEnum.OK, logDataGridVO);
        } catch (Exception e) {
            log.error("list logs error", e);
            return new BaseResponseVO<>(OctopusMsgEnum.SYSTEM_ERROR, null);
        }
    }
}
